const api = require('../../api/api.js');
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    site: {},
    siteId: 0,
    entId: 0,
    site_copy: {},
    isDisabled: true,
    region: [],
    region_copy: [],
    images: [],
    images_copy: [],
    imgUrl: app.globalData.imgUrl + 'siteImage/',
    tip: '',
    icon: '/imgs/icon_edit.png',
    delImgs: [],
    addImgs: []
  },
  onLoad(o) {
    let that = this;
    let siteId = o.siteId;
    let entId = o.entId;
    api.querySinglePlantation({
      data: {
        siteId: siteId
      },
      success(res) {
        let site = res.data.site;
        api.querySiteImages({
          data: {
            siteId: siteId
          },
          success(res) {
            console.log(res.data);
            let region = [site.province, site.city, site.county];
            let imgUrl = that.data.imgUrl;
            let tip = '';
            site.image = res.data.siteImages;
            site.image = site.image.map((i) => {
              return {
                imgUrl: imgUrl + i.image,
                imgID: i.id
              }
            });
            if (site.image.length === 9) {
              tip = '(最多九张)';
            }
            that.setData({
              site: site,
              siteId: siteId,
              entId,
              images: site.image.concat(),
              region: region,
              tip: tip
            });
            console.log(site);
          }
        });
      }
    });
    util.getLocalStorage(['role'], that);
  },
  edit() {
    let that = this;
    let isDisabled = !that.data.isDisabled;
    let icon;
    let tip = '';
    if (isDisabled === true) {
      wx.showModal({
        title: '提示',
        content: '取消编辑？',
        success(res) {
          if (res.confirm) {
            icon = '/imgs/icon_edit.png';
            if (that.data.images_copy.length === 9) {
              tip = '(最多九张)';
            }
            that.setData({
              tip: tip,
              site: that.data.site_copy,
              region: that.data.region_copy,
              images: that.data.images_copy.concat(),
              isDisabled: isDisabled,
              icon: icon
            });
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '编辑资料？',
        success(res) {
          if (res.confirm) {
            icon = '/imgs/icon_cancel.png';
            that.setData({
              site_copy: that.data.site,
              region_copy: that.data.region,
              images_copy: that.data.images.concat(),
              isDisabled: isDisabled,
              icon: icon
            });
          }
        }
      })
    }
  },
  delimg(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let images = this.data.images;
    let addImgs = this.data.addImgs;
    let img = images[index];
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success(e) {
        if (e.confirm) {
          images.splice(index, 1);
          if (img.imgID === -1) {
            for (let i = 0; i < addImgs.length; i++) {
              if (img.imgUrl === addImgs[i]) {
                addImgs.splice(i, 1);
              }
            }
          } else {
            that.data.delImgs.push(img.imgID);
          }
          that.setData({
            images: images,
            tip: ''
          });
        }
      }
    })
  },
  addimg() {
    let that = this;
    let images = this.data.images;
    let tip = '';
    wx.chooseImage({
      count: 9 - images.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        let tempFilePaths = res.tempFilePaths;
        that.data.addImgs.push(...tempFilePaths);
        tempFilePaths = tempFilePaths.map((i) => {
          return {
            imgUrl: i,
            imgID: -1
          }
        });
        images.push(...tempFilePaths);
        if (images.length === 9) {
          tip = '(最多九张)';
        }
        that.setData({
          images: images,
          tip: tip
        });
      }
    })
  },
  delImage(count) {
    let that = this;
    let imgs = this.data.delImgs;
    let len = imgs.length;
    let id = imgs[count];
    if (count === len) {
      return;
    }
    api.delSiteImage({
      data: {
        id
      },
      success(res) {
        that.delImage(++count);
      }
    });
  },
  addImage(count) {
    let that = this;
    let imgs = this.data.addImgs;
    let len = imgs.length;
    let img = imgs[count];
    let siteId = this.data.siteId;
    if (count === len) {
      return;
    }
    wx.getStorage({
      key: 'userId',
      success(res) {
        let userId = res.data;
        api.addFile({
          data: {
            userId: userId,
            path: 'siteImage',
            filePath: img
          },
          success(res) {
            let image = JSON.parse(res.data).fileName;
            api.addSiteImage({
              data: {
                image: image,
                siteId: siteId
              },
              success(res) {
                that.addImage(++count);
              }
            });
          }
        });
      }
    })
  },
  formSubmit(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定修改吗？',
      success(res) {
        if (res.confirm) {
          let siteId = that.data.siteId;
          let name = e.detail.value.name.trim();
          let province = that.data.region[0];
          let city = that.data.region[1];
          let county = that.data.region[2];
          let address = e.detail.value.address.trim();
          let remark = e.detail.value.remark.trim();
          if (name === '' || address === '' || remark === '') {
            wx.showToast({
              title: '请将内容填写完整！',
              icon: 'none'
            })
            return;
          }
          api.updatePlantation({
            data: {
              siteId,
              siteName: name,
              province,
              city,
              county,
              location: address,
              remarks: remark
            },
            success(res) {
              wx.showToast({
                title: '修改成功！',
                icon: 'none'
              });
              that.addImage(0);
              that.delImage(0);
              let pages = getCurrentPages();
              pages[pages.length - 2].onLoad();
              wx.navigateBack({
                delta: -1
              });
            }
          });
        }
      }
    })
  },
  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  goToSiteManagerPage(e) {
    let siteId = this.data.siteId;
    let entId = this.data.entId;
    wx.navigateTo({
      url: `/pages/manager/manager?siteId=${siteId}&entId=${entId}`,
    })
  }
})